package com.aco.party.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CookieUtil {

	private static Logger logger = LoggerFactory.getLogger(CookieUtil.class);

	private static final String COOKIE_DOMAIN = ConfigResource.getSystemProperty("cookieDomain");
	
	public static void addCookie(HttpServletResponse resp, int maxAge, String key, String value, String domain) {
		Cookie cookie = new Cookie(key, value);
		if (maxAge >= 0)
			cookie.setMaxAge(maxAge);
		if (domain != null) {
			cookie.setDomain(domain);
		} else {
			cookie.setDomain("");
		}
		cookie.setPath("/");
		resp.addCookie(cookie);
	}
	
	public static void addCookie(HttpServletResponse resp, String key, String value) {
		addCookie(resp, 3600 * 24 * 30 * 12, key, value, COOKIE_DOMAIN);
	}
	
	public static String getCookie(HttpServletRequest request, String key) {
		Cookie[] cookies = request.getCookies();
		if(cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie != null && cookie.getName().equals(key)) {
					return cookie.getValue();
				}
			}
		}
		return null;
	}
}
